import * as log4js from 'log4js';
import { Singleton } from './singleton';

/**
 * 给出日志操作接口
 */
export class Logger{
    l:log4js.Logger;
    constructor(l:log4js.Logger){
        this.l  =l;
    }
    info(message: string, ...args: any[]) {
        this.l.info(message, ...args);
    }
    warn(message: string, ...args: any[]) {
        this.l.warn(message, ...args);
    }
    error(message: string, ...args: any[]) {
        this.l.error(message, ...args);
    }
    trace(message: string, ...args: any[]) {
        this.l.trace(message, ...args);
    }
    debug(message: string, ...args: any[]) {
        this.l.debug(message, ...args);
    }
}

/**
 * Logger工厂
 */
export class LoggerFactory{
    private static cfg = {
        appenders: {
            console: { type: 'stdout' },
        },
        categories: {
            default: { appenders: ['console'], level: 'debug' },
        }
    };
    static init(path: string, fileName: string, category:string):Logger {
        (LoggerFactory.cfg.appenders as any)[fileName + "file"] =
            {
                type: 'dateFile', filename: path, pattern: fileName + '-yyyy-MM-dd.log',
                alwaysIncludePattern: true, backups: 100, level: "debug", category: category 
            };

        (LoggerFactory.cfg.categories as any)[category] = { appenders: ['console', fileName + "file"], level: 'debug' };

        log4js.configure(LoggerFactory.cfg);
        return new Logger(log4js.getLogger(category));
    }
}

/**
 * 日志工厂基类
 * 必须实现虚方法 getInitCategory
 */
export abstract class LogFactoryBase extends Singleton{
    private path:string = "";
    private fileName:string = "";
    private isInited = false;

    abstract getInitCategory():string;

    init(path: string, fileName: string){
        if (!this.isInited){
            this.path = path;
            this.fileName = fileName;
            LoggerFactory.init(path, fileName, this.getInitCategory());
            this.isInited = true;
        }
    }

    /**
     * 获得log4js的Logger
     * @param category 日志分类名称　
     */
    getLogger(category:string):Logger{
        if (!this.isInited){
            throw new Error("LogFactory have no initialized");
        }
        return LoggerFactory.init(this.path, this.fileName, category);
    }
}

/**
 * 日志工厂
 * 其默认日志分类名称为log
 */
export class LogFactory extends LogFactoryBase{
    getInitCategory(): string {
        return "Log";
    }
}